import {
  SearchOutlined,
  AppstoreOutlined,
  CaretRightOutlined,
  CaretDownOutlined,
  FileAddTwoTone,
  PlusOutlined,
} from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Input, Image, Button, Dropdown, Tooltip, message } from "antd";
import type { MenuProps } from "antd";
import dayjs from "dayjs";
import { forEach, head, findIndex, last, cloneDeep, find } from "lodash";
import { useState, forwardRef, useEffect, useRef } from "react";

import U454 from "../../assets/imgs/u454.png";
import Remove from "../Remove";
import { AtaParams } from "./index";

import {
  useAnalysisTask,
  TaskParam,
} from "~/components/Visualization/store/useTaskState";
import {
  useAtaParamsList,
  getCustomParamDocument,
} from "~/hooks/Visualization/use-visualization-api";
import { ParamsQuery } from "~/hooks/Visualization/visualization";
import { ParamType, Mutation } from "~/modules/api-server/types";
import { MutationParamsArgs, ActType } from "~/modules/api-server/types2";
import { ChartType, ChartItem } from "~/modules/workspace/models";
import { useWorkSpace } from "~/modules/workspace/store/use-workspace";
import { getContent } from "~/plugins/api-server";
import eventBus from "~/utils/event";
import "./parameterList.scss";
import { formatDate } from "~/modules/shared/utils/common";

interface Props {
  AddCustom: Function;
}

const ParameterList = (props: Props, ref: any) => {
  // 获取task信息
  const { analysisTask, updateTask } = useAnalysisTask();
  // 获取工作区配置
  const { workSpace, update } = useWorkSpace();
  const removeRef = useRef();
  // 获取参数列表
  const ataParamsQuery: ParamsQuery = {
    aircraftId: analysisTask.aircraftId,
    startTime: formatDate(analysisTask.startTime),
    endTime:
      analysisTask.endTime === analysisTask.startTime
        ? formatDate(dayjs(analysisTask.endTime).add(1, "days"))
        : analysisTask.endTime,
  };
  const paramsRes: any = useAtaParamsList(ataParamsQuery);
  // 页面渲染参数列表
  const [paramsList, setParamsList] = useState<AtaParams[]>([]);
  const [filterParamsList, setFilterParamsList] = useState<any[]>([]);
  // 监控工作区图表
  const [mark, setMark] = useState<number>(0);
  const [items, setItems] = useState<any>([]);
  useEffect(() => {
    const paramBtns: any[] = [{ key: 1, label: "添加到新图表" }];
    if (workSpace.splitCharts.length > 0) {
      paramBtns.push({ key: 2, label: `添加到已有图表`, children: [] });
      forEach(workSpace.splitCharts, (t, i) => {
        paramBtns[1].children.push({ key: i + 3, label: `${t.name}` });
      });
    }
    setItems(paramBtns);
  }, [workSpace.splitCharts.length, mark]);
  useEffect(() => {
    eventBus.emit(`flightParamsList`, paramsRes?.atasParams);
    const taskParams: TaskParam[] = [];
    const data: any[] = [];
    data.push({
      name: "自定义",
      code: "",
      params: analysisTask.customParams,
      islist: false,
    });
    forEach(paramsRes?.atasParams, (item) => {
      item.islist = false;
      data.push(item);
      forEach(item.params, (m) => {
        taskParams.push(m);
      });
    });

    analysisTask.taskParams = taskParams;
    updateTask(analysisTask);
    setParamsList(data);
    setFilterParamsList(data);
  }, [paramsRes, analysisTask.customParams.length]);

  // 创建、更新自定义参数
  const [addOrEditCustomParam, { data: addOrEditData }] = useMutation<
    Mutation,
    MutationParamsArgs
  >(getCustomParamDocument, {
    client: getContent().explorer_apiServer,
  });
  useEffect(() => {
    if (addOrEditData) {
      const num: number = findIndex(analysisTask.customParams, (item) => {
        return item.name === checkParam.name;
      });
      analysisTask.customParams.splice(num, 1);
      updateTask(analysisTask);
    }
  }, [addOrEditData]);

  const [isSubsetHover, onSetSubsetHover] = useState("");
  const [checkParam, setCheckParam] = useState<any>();

  const onListItem = (value: AtaParams, index: number) => {
    const list = [...paramsList];
    list[index].islist = !list[index].islist;
    setParamsList(list);
  };

  const [delText, setDelText] = useState<string>("");
  const onClick: MenuProps["onClick"] = ({ key }) => {
    if (Number(key) === 1) {
      const chartItem = {
        name: checkParam.name,
        chartType: ChartType.LINE,
        upperLimit: "",
        lowerLimit: "",
        XOffset: "",
        YOffset: "",
        IsTop: false,
        data: [
          {
            title: checkParam.name,
            color: "#E0756C",
            paramType: checkParam.expression
              ? ParamType.Custom
              : ParamType.Field,
            expression: checkParam.expression ? checkParam.expression : "",
          },
        ],
      };
      workSpace.splitCharts.push(chartItem);
      if (
        (600 - 32 - 60 * (workSpace.splitCharts.length + 1)) /
          workSpace.splitCharts.length <=
        100
      ) {
        workSpace.setting.chartsHeight = "100";
      } else {
        workSpace.setting.chartsHeight = String(
          (600 - 32 - 60 * (workSpace.splitCharts.length + 1)) /
            workSpace.splitCharts.length
        );
      }
    } else if (key === "a") {
      props.AddCustom("edit", checkParam);
    } else if (key === "b") {
      setDelText(`是否删除自定义参数 ${checkParam.name} ？`);
      // setDelparam(record.name);
      removeRef.current && (removeRef.current as any).onDelete();
    } else {
      let chartName: string = "";
      forEach(items[1].children, (k) => {
        if (k.key === Number(key)) {
          chartName = k.label;
        }
      });
      forEach(workSpace.splitCharts, (item: ChartItem, index: number) => {
        if (item.name === chartName) {
          if (
            find(item.data, (it) => {
              return it.title === checkParam.name;
            })
          ) {
            message.error(`图表 ${item.name} 已包含参数 ${checkParam.name}`);
          } else {
            const chartParam = {
              title: checkParam.name,
              color: "#E0756C",
              paramType: checkParam.expression
                ? ParamType.Custom
                : ParamType.Field,
              expression: checkParam.expression,
            };
            item.data.push(chartParam);
          }
        }
      });
    }
    update(workSpace);
    setMark(mark + 1);
  };

  const paramsDiv = paramsList?.map((item: AtaParams, index: number) => {
    return (
      <div key={index}>
        <div
          className="ata-params-list"
          onClick={() => onListItem(item, index)}
        >
          <div className="itemPStyle">
            {item.name === "自定义" ? (
              <Image width={16} preview={false} src={U454} />
            ) : (
              <AppstoreOutlined
                style={{
                  color: item.islist ? "#5E7CE0" : "#BCBCBC",
                }}
              />
            )}
            <span className="pl-6px">{item.name}</span>
          </div>
          {item.islist ? (
            <CaretDownOutlined className="color-#5E7CE0! mt-12px" />
          ) : (
            <CaretRightOutlined className="mt-12px" />
          )}
        </div>
        <div>
          {item.islist
            ? item.params.map((m: any, i: number) => {
                return (
                  <div
                    key={i}
                    onMouseOver={() => onSetSubsetHover(item.name + m.name)}
                    onMouseOut={() => onSetSubsetHover("")}
                  >
                    <div className="ata-params-list-item">
                      {m.quality ? (
                        <Tooltip
                          placement="rightTop"
                          title={
                            <>
                              {m.quality.map((t: string, n: number) => {
                                return (
                                  <p
                                    key={n}
                                    style={{ lineHeight: "32px", margin: "0" }}
                                  >
                                    航班： {head(t.split(":"))}
                                    <span style={{ marginLeft: "16px" }}>
                                      质量：{last(t.split(":"))}
                                    </span>
                                  </p>
                                );
                              })}
                              <p style={{ lineHeight: "32px", margin: "0" }}>
                                描述： {m.desc}
                              </p>
                            </>
                          }
                          overlayStyle={{ width: "300px", maxWidth: "300px" }}
                          arrowPointAtCenter
                        >
                          <p className=" truncate mb-0">{m.name}</p>
                        </Tooltip>
                      ) : (
                        <Tooltip placement="rightTop" title={m.expression}>
                          <p className="truncate mb-0">{m.name}</p>
                        </Tooltip>
                      )}

                      {isSubsetHover === item.name + m.name ? (
                        <Dropdown menu={{ items, onClick }} trigger={["click"]}>
                          <Button
                            type="text"
                            icon={<FileAddTwoTone />}
                            onClick={() => onSelectParam(m)}
                          />
                        </Dropdown>
                      ) : null}
                    </div>
                  </div>
                );
              })
            : null}
        </div>
      </div>
    );
  });

  // 添加自定义参数
  const onAddCustomParams = () => {
    props.AddCustom("add");
  };
  const onSelectParam = (value: any) => {
    let data = [...items];
    if (value.expression) {
      data = [
        data[0],
        data[1],
        { key: "a", label: "修改" },
        { key: "b", label: "删除" },
      ];
    } else {
      data = [data[0], data[1]];
    }
    setItems(data);
    setCheckParam(value);
  };
  // 删除自定义参数
  const onDelCustomParam = () => {
    const param = {
      ...checkParam,
      tid: analysisTask.id,
      act_type: ActType.Delete,
    };
    addOrEditCustomParam({
      variables: {
        input: param,
      },
    });
  };

  // 过滤参数
  const onFilterParams = (value: string) => {
    const list = cloneDeep(filterParamsList);
    let data: any[] = [];
    if (value === "") {
      data = list;
    } else {
      forEach(list, (item, index) => {
        const arr: any = {
          name: item.name,
          code: item.code,
          isList: false,
          params: [],
        };
        forEach(item.params, (it) => {
          if (it.name.indexOf(value) !== -1) {
            arr.islist = true;
            arr.params.push(it);
          }
        });
        if (arr.params.length > 0) {
          data.push(arr);
        }
      });
    }
    setParamsList(data);
  };
  return (
    <>
      <div className="screenStyle">
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <p className="titleStyle"> 选取参数</p>
          <Button
            type="text"
            icon={
              <PlusOutlined style={{ fontSize: "18px", color: "#5E7CE0" }} />
            }
            onClick={() => onAddCustomParams()}
          />
        </div>

        <Input
          prefix={<SearchOutlined />}
          placeholder="请输入"
          onChange={(e) => onFilterParams(e.target.value)}
        />
      </div>
      <div className="paramsStyle">{paramsDiv}</div>
      <Remove ref={removeRef} delText={delText} onDelTask={onDelCustomParam} />
    </>
  );
};
export default forwardRef(ParameterList);
